﻿using System;

namespace CommandPattern;

//教官：负责调用命令对象执行请求
public class Invoker(Command command)
{
    public void ExecuteCommand() {command.Action();}

    public void Undo() { command.Undo(); }
}

//命令抽象类
public abstract class Command(Receiver receiver)
{
    //命令需要知道接收者是谁
    protected readonly Receiver Receiver = receiver;

    public abstract void Action();
    public abstract void Undo();
}

//具体命令
public class RunningCommand(Receiver receiver) : Command(receiver)
{
    public override void Action() { Receiver.Running(); }

    public override void Undo() { Receiver.UndoRunning(); }
}

public class EatingCommand(Receiver receiver) : Command(receiver)
{
    public override void Action(){Receiver.Eating();}

    public override void Undo(){Receiver.UndoEating();}
}

//命令的接收者：学生
public class Receiver
{
    public void Running() { Console.WriteLine("长跑训练"); }

    public void Eating() { Console.WriteLine("解散吃饭"); }

    public void UndoRunning() { Console.WriteLine("撤销跑步，回到起点"); }

    public void UndoEating() { Console.WriteLine("撤销吃饭，重新集合"); }
}

public static class Program
{
    public static void Main()
    {
        Receiver receiver = new();
        Command command1 = new RunningCommand(receiver);
        Command command2 = new EatingCommand(receiver);

        Invoker invoke1 = new(command1);
        invoke1.ExecuteCommand();
        invoke1.Undo();
        Console.WriteLine("\n切换命令\n");
        Invoker invoke = new(command2);
        invoke.ExecuteCommand();
        invoke.Undo();
    }
}